import G6 from '@antv/g6';
import * as events from '../../../utils/event/componentEvent';
import { randomKey } from '../../../utils/utils';
//  右键
G6.registerBehavior('context-menu', {
  getEvents() {
    return {
      click: 'onClick',
      'edge:contextmenu': 'onEdgeContextmenu', // 右键线
      'node:contextmenu': 'onNodeContextmenu', // 右键节点
    };
  },
  edgeConextMenu(ev) {
    if (this.edgeConextMenu) {
      this.edgeConextMenu.style.display = 'none';
    }
    if (this.nodeConextMenu) {
      this.nodeConextMenu.style.display = 'none';
    }
  },
  onEdgeContextmenu(ev) {
    this.edgeConextMenu = ev.currentTarget._edgeMenu;
    const edge = ev.item;
    const pos = this.graph.getClientByPoint(ev.x, ev.y);
    this.edgeConextMenu.style.display = 'block';
    this.edgeConextMenu.style.left = pos.x + 'px';
    this.edgeConextMenu.style.top = pos.y + 'px';
    this.edgeConextMenu.onclick = (e) => {
      if (e.target.className === 'flow-menu-item') {
        //删除
        if (e.target.id === 'delete') {
          this.graph.removeItem(edge);
          this.edgeConextMenu.style.display = 'none';
        }
      }
    };
  },
  onNodeContextmenu(ev) {
    this.nodeConextMenu = ev.currentTarget._nodeMenu;
    const node = ev.item;
    const model = node.getModel();
    const pos = this.graph.getClientByPoint(ev.x, ev.y);
    const w = this.nodeConextMenu.getAttribute('w')
      ? (document.body.offsetWidth - Number(this.nodeConextMenu.getAttribute('w'))) / 2
      : 0;
    const h = this.nodeConextMenu.getAttribute('h')
      ? (document.body.offsetHeight - Number(this.nodeConextMenu.getAttribute('h'))) / 2
      : 0;

    this.nodeConextMenu.style.display = 'block';
    this.nodeConextMenu.style.left = pos.x - w + 'px';
    this.nodeConextMenu.style.top = pos.y - h + 'px';
    this.nodeConextMenu.onclick = (e) => {
      if (e.target.className === 'flow-menu-item') {
        //编辑
        if (e.target.id === 'edit') {
          this.nodeConextMenu.style.display = 'none';
          events.eventEmitter.emit(events.OPEN_STRATEGY_NODE, {
            data: {
              ...model,
            },
            actionType: 'update',
            modelTitle: '编辑节点',
          });
        }
        //复制
        if (e.target.id === 'copy') {
          const copyModel = Object.assign({}, JSON.parse(JSON.stringify(model)), {
            id: randomKey(),
            name: '',
            x: ev.x + 100,
          });

          this.nodeConextMenu.style.display = 'none';
          events.eventEmitter.emit(events.OPEN_STRATEGY_NODE, {
            data: {
              ...copyModel,
            },
            actionType: 'copy',
            modelTitle: '复制节点',
          });
        }
        //删除
        if (e.target.id === 'delete') {
          this.graph.removeItem(node);
          this.nodeConextMenu.style.display = 'none';
        }
      }
    };
  },
});
